import type { App } from 'vue'
import { ElNotification, ElMessage } from 'element-plus'
import { ErrorHandler, setNotificationHandler } from '@/utils/error-handler'
import type { AppError } from '@/types/errors'

// 通知显示函数
const showNotification = (message: string, type: 'success' | 'warning' | 'error' | 'info') => {
  ElNotification({
    title: getNotificationTitle(type),
    message,
    type,
    duration: type === 'error' ? 0 : 4500, // 错误通知不自动关闭
    showClose: true
  })
}

// 获取通知标题
const getNotificationTitle = (type: string): string => {
  const titles = {
    success: '成功',
    warning: '警告',
    error: '错误',
    info: '信息'
  }
  return titles[type as keyof typeof titles] || '通知'
}

// 全局错误处理插件
export default {
  install(app: App) {
    // 设置错误处理器的通知函数
    setNotificationHandler(showNotification)

    // Vue 错误处理
    app.config.errorHandler = (err, _instance, info) => {
      console.error('Vue Error:', err, info)
      
      const error = ErrorHandler.createError(
        'UNKNOWN_ERROR' as any,
        '应用程序发生错误',
        { originalError: err, info }
      )
      
      ErrorHandler.handle(error)
    }

    // 未捕获的 Promise 错误
    window.addEventListener('unhandledrejection', (event) => {
      console.error('Unhandled Promise Rejection:', event.reason)
      
      const error = ErrorHandler.createError(
        'UNKNOWN_ERROR' as any,
        '异步操作失败',
        { reason: event.reason }
      )
      
      ErrorHandler.handle(error)
      event.preventDefault()
    })

    // 全局 JavaScript 错误
    window.addEventListener('error', (event) => {
      console.error('Global Error:', event.error)
      
      const error = ErrorHandler.createError(
        'UNKNOWN_ERROR' as any,
        '脚本执行错误',
        { 
          message: event.message,
          filename: event.filename,
          lineno: event.lineno,
          colno: event.colno,
          error: event.error
        }
      )
      
      ErrorHandler.handle(error)
    })

    // 提供全局方法
    app.config.globalProperties.$notify = {
      success: (message: string) => showNotification(message, 'success'),
      warning: (message: string) => showNotification(message, 'warning'),
      error: (message: string) => showNotification(message, 'error'),
      info: (message: string) => showNotification(message, 'info')
    }

    app.config.globalProperties.$message = {
      success: (message: string) => ElMessage.success(message),
      warning: (message: string) => ElMessage.warning(message),
      error: (message: string) => ElMessage.error(message),
      info: (message: string) => ElMessage.info(message)
    }

    app.config.globalProperties.$handleError = (error: AppError) => {
      ErrorHandler.handle(error)
    }
  }
}

// 导出工具函数
export { showNotification, ErrorHandler }